package com.postsuperman.proxypool.common.http;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.postsuperman.proxypool.pojo.HttpProxy;
import org.apache.http.HttpHost;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.util.Map;

/**
 * @author ： Lwl postserupman
 * @Description TODO
 * @Date 2019/2/27 12:06
 * @Version 1.0
 */
public class HttpManager {

    private static Integer TIME_OUT = 5000;

    private HttpManager() {
    }

    public static String get(String url) {

        try {
            return HttpUtil.get(url, TIME_OUT);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String get(String url, Map<String, Object> mapParam) {
        try {
            return HttpUtil.get(url, mapParam, TIME_OUT);
        } catch (Exception ex) {
        }
        return null;
    }

    public static String get(String url, HttpProxy proxy) {

        return get(url, null, proxy);
    }

    public static String get(String url, Map<String, Object> mapParam, HttpProxy proxy) {
        try {
        HttpRequest httpRequest = HttpUtil.createGet(url)
                .timeout(TIME_OUT);

        if (chkProxy(proxy)) {
            httpRequest.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getIp(), proxy.getPort())));
        }

        if (mapParam != null) {
            httpRequest.form(mapParam);
        }

        HttpResponse httpResponse = httpRequest.execute();
        return httpResponse.body();
        } catch (Exception ex) {
        }
        return null;
    }

    public static boolean chkProxy(HttpProxy proxy) {
        if (proxy == null) {
            return false;
        }
        return chkProxy(proxy.toHttpHost());
    }

    public static boolean chkProxy(HttpHost proxy) {

        if (proxy == null) {
            return false;
        }

        Socket socket = null;
        try {
            socket = new Socket();
            InetSocketAddress endpointSocketAddr = new InetSocketAddress(proxy.getHostName(), proxy.getPort());
            socket.connect(endpointSocketAddr, 3000);
            return true;
        } catch (IOException e) {
            return false;
        } finally {
            IOUtils.closeQuietly(socket);
        }
    }
}
